﻿using Clipboard.Tools;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Clipboard.Services
{
    public class EmailService
    {
        private readonly EmailHelper _emailHelper;
        private static IMemoryCache _cache = new MemoryCache(new MemoryCacheOptions());  // 使用默认的内存缓存

        public EmailService()
        {
            // 初始化邮件发送帮助类，传入SMTP服务器的配置  
            _emailHelper = new EmailHelper("smtp.163.com", 465, "13317549437@163.com", "GRfziaUQBLnKneg9");
        }

        public async Task<bool> SendVerificationCodeAsync(string userEmail)
        {
            // 发送验证邮件
            var code = GenerateVerificationCode();
            bool result = await _emailHelper.SendVerificationEmailAsync(userEmail, code);

            if (result)
            {
                // 保存验证码到内存缓存中，设置有效期为 5 分钟
                _cache.Set(userEmail, code, TimeSpan.FromMinutes(5));
            }
           

            return result;
        }

        //验证码
        public bool ValidateVerificationCode(string userEmail, string code)
        {
            // 从缓存中获取验证码
            var storedCode = _cache.Get(userEmail) as string;

            // 如果缓存中没有验证码，返回验证失败
            if (string.IsNullOrEmpty(storedCode))
            {
                return false;
            }

            // 比较验证码是否匹配
            return storedCode == code;
        }

        private string GenerateVerificationCode()
        {
            Random random = new Random();
            return random.Next(100000, 999999).ToString(); // 生成6位验证码
        }
    }
}
